import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_tweet.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/tweet/publish_tweet.dart';
import 'package:osc/ui/pages/tweet/tweet_content.dart';
import 'package:osc/ui/pages/tweet/tweet_detail.dart';
import 'package:osc/ui/widgets/button/pd_button.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///动弹
class TweetList extends StatefulWidget {
  final int type;
  final int userId;
  final bool needLogin;
  final bool enableLoadMore;

  /// type  [ 1：最新动弹，2：热门动弹 ]，与authorId相斥，只传一个
  const TweetList({Key key, this.type, this.userId, this.needLogin = false, this.enableLoadMore = true}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new TweetListState(type, userId, needLogin, enableLoadMore);
  }
}

class TweetListState extends State<TweetList> with AutomaticKeepAliveClientMixin<TweetList> {
  final int type;
  final int userId;
  final bool needLogin;
  final bool enableLoadMore;
  TweetListState(this.type, this.userId, this.needLogin, this.enableLoadMore);

  HttpRepository httpRepository;
  int size = 0;
  bool isLoadedData = false;
  bool deletable = false;

  int requestCount;
  int totalResults;
  int responseCount;
  String pageToken;

  double paddingChildVertical = Dimens.gap_view_normal;


  List<OscTweet> list;
  List<int> blacklist;

  RefreshController controller = RefreshController(initialRefresh: true);


  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    deletable = userId == OscUserManager().getUserId();
    blacklist = OscUserManager().user?.blacklist;
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: controller,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: enableLoadMore,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if(needLogin && !OscUserManager().isLogin()){
            return NoDataWidget(text: StringIds.userNoLogin,);
          } else {
            if (size == 0) {
              return NoDataWidget();
            } else {
              return buildListItem(index);
            }
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLineBigger();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
      ),
    );
  }

  buildListItem(int index){
    OscTweet item = list.elementAt(index);

    final GlobalKey<TweetContentState> anchorKey = GlobalKey<TweetContentState>();
    return GestureDetector(
      onTap: (){
        double height = anchorKey.currentContext.size.height;
        jump2PageForResult(TweetDetail(tweet: item, expandedHeight: height,));
      },
      onLongPress: (){
        showOptionDialog(index);
      },
      child: Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TweetContent(tweet: item, key: anchorKey,),
            buildBottom(index, item, anchorKey),
          ],
        ),
      ),
    );
  }


  buildBottom(int index, OscTweet tweet, GlobalKey<TweetContentState> anchorKey){
    return Padding(
      padding: EdgeInsets.symmetric(vertical: paddingChildVertical),
      child: Row(
        children: <Widget>[
          buildBottomItem("ic_forward", "转发", (){
            String originContent = tweet.content;
            if(tweet.about != null && !StringUtil.isEmpty(tweet.about.content)){
              originContent = StringUtil.clearHtmlContent(tweet.about.content);
            }
            jumpToPageForResult(PublishTweet(
              originAuthorName: tweet.author.name,
              originContent: originContent,
              tweetContent: StringUtil.clearHtmlContent(tweet.content),
              aboutFromTweetId: tweet.id,
              aboutId: tweet.about?.id??tweet.id,
            ));
          }),
          buildBottomItem("ic_comment_30", tweet.commentCount > 0? "${tweet.commentCount}":"评论", (){
            double height = anchorKey.currentContext.size.height;
            jumpToPageForResult(TweetDetail(tweet: tweet, expandedHeight: height,));
          }),
          buildBottomItem(tweet.liked? "ic_thumbup_actived" : "ic_thumb_normal", tweet.likeCount > 0? "${tweet.likeCount}":"赞", (){
            reverseTweetLike(tweet.id, index);
          }),
        ],
      ),
    );
  }

  buildBottomItem(String imageName, String text, Function onTap){
    return Expanded(
        child: GestureDetector(
          onTap: onTap,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(PdUtil.getImagePath(imageName), width: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitWidth,),
              buildText(" $text", Colors.black54, Dimens.font_sp10)
            ],
          ),
        )
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }


  showOptionDialog(int index){
    OscTweet tweet = list.elementAt(index);
    showDialog(
        context: context,
      builder: (BuildContext context){
          return AlertDialog(
            contentPadding: EdgeInsets.zero,
            actions: <Widget>[
              PdButton(
                data: "取消",
                onTap: (){
                  Navigator.pop(context);
                },
                textStyle: MyTextStyle.GREEN_BUTTON,
              ),
            ],
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                buildOptionItem("复制", (){
                  Clipboard.setData(ClipboardData(text: StringUtil.clearHtmlContent(tweet.content)));
                  showTips("已复制到粘贴板");
                  Navigator.pop(context);
                }),
                buildOptionItem("转发", (){
                  Navigator.pop(context);
                }),
                Offstage(
                  offstage: !deletable,
                  child: buildOptionItem("删除", (){
                    deleteTweet(tweet.id, index);
                    Navigator.pop(context);
                  }),
                )
              ],
            ),
          );
      }
    );
  }

  buildOptionItem(String data, Function onTap){
    return ListTile(
      title: Text(data, style: MyTextStyle.USER_LIST_TITLE,),
      onTap: onTap,
    );
  }

  refresh() async{
    pageToken = null;
    list?.clear();
    await loadMore();
  }


  loadMore() async{
    isLoadedData = true;
    await httpRepository.getTweetList(type: type, pageToken: pageToken, authorId: userId).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscTweet> result = resp.result;
        if(result != null){
          List<OscTweet> tempItems = List.from(result.items);
          List<OscTweet> tempList = List();
          if(blacklist == null || blacklist.isEmpty){
            tempList = tempItems;
          } else {
            for (OscTweet tweet in tempItems) {
              if (!blacklist.contains(tweet.author.id)) {
                tempList.add(tweet);
              }
            }
          }
          responseCount = result.responseCount;
          requestCount = result.requestCount;
          if(StringUtil.isEmpty(pageToken)){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          pageToken = result.nextPageToken;
          size = list?.length??0;
        }
      }
    });
    if(mounted){
      setState(() {
        controller.loadComplete();
        controller.refreshCompleted();
      });
    }
  }

  deleteTweet(int id, int index) async{
    await httpRepository.deleteTweet(id).then((resp){
      if(resp.success){
        list.removeAt(index);
        if(mounted){
          setState(() {

          });
        }
      } else {
        showTips(resp.message);
      }
    });
  }

  reverseTweetLike(int id, int index) async{
    await httpRepository.reverseTweetLike(sourceId: id).then((resp){
      if(resp.success){
        list.elementAt(index).liked = resp.result.liked;
        list.elementAt(index).likeCount = resp.result.likeCount;
        if(mounted){
          setState(() {

          });
        }
      } else {
        showTips(resp.message);
      }
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }
}
